package com.booktrading.controller;

import com.booktrading.model.Book;
import com.booktrading.model.User;
import com.booktrading.service.BookService;
import com.booktrading.service.DashboardService;
import com.booktrading.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

import java.util.List;
import java.util.Map;

@Controller
public class HomeController {

    @Autowired
    private BookService bookService;
    
    @Autowired
    private UserService userService;
    
    @Autowired
    private DashboardService dashboardService;

    @GetMapping("/")
    public String index(Model model) {
        // 获取最新上架的8本书籍
        List<Book> latestBooks = bookService.getAllOnSaleBooks();
        if (latestBooks.size() > 8) {
            latestBooks = latestBooks.subList(0, 8);
        }
        
        model.addAttribute("latestBooks", latestBooks);
        
        return "index";
    }
    
    @GetMapping("/login")
    public String login() {
        return "user/login";
    }
    
    @GetMapping("/dashboard")
    public String dashboard(Model model) {
        // 获取当前登录用户
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        User user = userService.getUserByUsername(auth.getName());
        
        // 获取用户的统计数据
        Map<String, Integer> stats = dashboardService.getUserDashboardStats(user.getId());
        model.addAttribute("stats", stats);
        
        return "dashboard";
    }
} 